import React, { Component, PropTypes } from 'react';
import {
  Text,
  View,
  ScrollView,
  StyleSheet,
  DeviceEventEmitter,
  Platform,
  Image,
  Animated,
  TouchableOpacity,
  Dimensions,
  NativeAppEventEmitter,
  InteractionManager
} from 'react-native';

import ScrollableTabView from 'react-native-scrollable-tab-view';
import CustomListView from '../global/CustomListView';

import ProgressBar from '../global/ProgressBar';
import DefaultTabBar from '../global/scrollableTabView/DefaultTabBar';
import Button from '../global/scrollableTabView/Button';

import OwnerList from './ownerList';
import SellRecordList from './sellRecordList';
import styles from './sellRecordStyle';
import api from '../../services/api';

const windowHeight = Dimensions.get('window').height;

class SellRecordInfo extends Component {
    constructor(props) {
		super(props);

        this.heightTop = (windowHeight / 2) *(-1);

		this.state = {
			isLoading: true,
			isRefreshing: false,
			tab: 0,
            isShow: false,
            display: 'none',
            num: [0, 0],
            selectedTab:"0"
		};

		// this._getTabHeight = this._getTabHeight.bind(this);
		this._onChangeTab = this._onChangeTab.bind(this);

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

  componentDidMount() {
        // this.onLoad();
    }

    // onLoad(){
    //     if(this.state.noData){
    //         this.setState({ noData: false});
    //     }

    //     this._withdrawByList._pullToRefreshListView.beginRefresh(true);
    // }

    // componentWillMount() {
		// this._retrieveDetails();
	// }

    // componentDidMount(){
        // this.getNotApprovedCount();

        // let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
        // this._subcribOwner = Emitter.addListener('owner.onload', this.onLoad.bind(this));
    // }

    // onLoad(){
    //     InteractionManager.runAfterInteractions(async() => {
    //         this._regListView && this._regListView.wrappedInstance.onLoad();
    //         this._notApproveListView && this._notApproveListView.wrappedInstance.onLoad();
    //     });
    // }

 //    async getNotApprovedCount(){
 //        let res, arr = [0 , 0];
 //        res = await api.post('/housekeeper/notapprovedcount',{});
 //        if(res){
 //            arr[1] = res.data;
 //        }

 //        this.setState({ num : arr});
 //    }

    _onChangeTab({ i, ref }) {
		this.setState({ tab: i });
	}

    // updateMarkNum(arr){
    //     this.setState({ num : arr});
    // }

    // _onNavigatorEvent(event){
    //     if (event.type === 'ScreenChangedEvent') {
	// 		if (event.id === 'didAppear') {//出现时
    //
	// 		}
	// 	}
    // }

    // componentWillUnmount(){
    //     this._subcribOwner && this._subcribOwner.remove();
    // }
    
    // async _getWithdrawList(){
    //     let list;

    //     //need to clear ListRowRefsCache manually
    //     this._withdrawByList._pullToRefreshListView.clearListRowRefsCache();

    //     list = await api.post('/order/tradelist', {
    //                page:1
    //             });
    //    this.list = {};

    //    if(Platform.OS == 'ios') {
    //        this._endWithdrawList(list.data);
    //    } else {
    //        setTimeout(() => {
    //            this._endWithdrawList(list.data);
    //        }, 300);
    //    }
    // }

    // _endWithdrawList(list){

    //     this.totalpage = list.total_page;
    //     list = list.res;

    //     // console.log("###", list);
    //     if(list==null || list.length==0){
    //         this.setState({noData: true});
    //         return;
    //     }

    //     for (var i = 0; i < list.length; i++) {
    //         let dateArr = list[i].trade_time.split("-");
    //         if(this.list[dateArr[0]+'年'+dateArr[1]+'月']){
    //             this.list[dateArr[0]+'年'+dateArr[1]+'月'].push(list[i]);
    //         }else{
    //             this.list[dateArr[0]+'年'+dateArr[1]+'月'] = [list[i]];
    //         }
    //     }

    //     let list_copy = {...this.list};
    //     // this._updateListView();cloneWithRowsAndSections
    //     this.setState({ currentPage: 1 });
    //     this._withdrawByList && this._withdrawByList.setState({
    //         dataSource: this._withdrawByList._dataSource.cloneWithRowsAndSections(list_copy)
    //     });

    //     this._activityIndicator && this._activityIndicator.setState({ visible: false,});
    //     this._withdrawByList && this._withdrawByList._pullToRefreshListView.endRefresh(false);
    // }

    // async _retrieveNextPage() {
    //     let page, list;
    //     if (this.state.currentPage !== this.totalpage) {
    //         page = this.state.currentPage + 1;
    //         this.setState({ currentPage: page });

    //         list = await api.post('/order/tradelist', {
    //                    page:page
    //                 });

    //         if(list.data){
    //             const newData = list.data.res;
    //             for (var i = 0; i < newData.length; i++) {
    //                 let dateArr = newData[i].trade_time.split("-");
    //                 if(this.list[dateArr[0]+'年'+dateArr[1]+'月']){
    //                     this.list[dateArr[0]+'年'+dateArr[1]+'月'].push(newData[i]);
    //                 }else{
    //                     this.list[dateArr[0]+'年'+dateArr[1]+'月'] = [newData[i]];
    //                 }
    //             }

    //             // newData.map((item, index) => this.list.push(item));

    //             this._withdrawByList.setState({
    //                 dataSource: this._withdrawByList._dataSource.cloneWithRowsAndSections(this.list),
    //             });

    //             this._withdrawByList._pullToRefreshListView.endLoadMore(false);
    //         }

    //     }else{
    //         this._withdrawByList._pullToRefreshListView.endLoadMore(true);
    //     }

    // }

    // _onRefresh(){
    //     this._getWithdrawList();
    // }

    // _onLoadMore(){
    //     this._retrieveNextPage();
    // }


    // _renderFloatSectionHeader(sectionID){
    //     return (
    //         <View style={{paddingLeft:15,paddingTop:5,paddingBottom:5,backgroundColor:'#fff',borderBottomWidth:StyleSheet.hairlineWidth,borderColor:'#DEDEDE'}}>
    //             <Text style={{color: '#565656'}}>{sectionID}</Text>
    //         </View>
    //     )
    // }

    // _renderSectionHeader(sectionData, sectionID){
    //     return (
    //         <View style={{paddingLeft:15,paddingTop:5,paddingBottom:5,backgroundColor:'#fff',borderBottomWidth:StyleSheet.hairlineWidth,borderColor:'#DEDEDE'}}>
    //             <Text style={{color: '#565656'}}>{sectionID}</Text>
    //         </View>
    //     )
    // }


    // _renderRow(rowData, sectionID, rowID){

    //     return (
    //         <View style={[styles.searchItem,{marginLeft:0,flexDirection: 'row',alignItems:'center',justifyContent:'space-between'}]}>
    //             <View style={{paddingLeft: 15,}}>
    //                 <Text style={{fontSize: 13, color: '#555555',}}>222</Text>
    //                 <Text style={{fontSize: 12, color: '#7B7B7B', marginTop: 5, }}>333</Text>
    //             </View>
    //             <View style={{marginRight: 15,}}>
    //                 <Text style={{fontSize: 13, color: '#EA5404',textAlign:'right'}}>444</Text>
    //                 <Text style={{fontSize: 12, color: '#7B7B7B', marginTop: 5, textAlign:'right'}}>555</Text>
    //             </View>
    //         </View>
    //     );
    // }
    // _onChangeTab(index){
    //   this.setState({
    //     selectedTab:index,
    //   })
    // }
    _pressItem(){

    }

    _renderTab(name, page, isTabActive, onPressHandler) {
      const {textStyle, markStyle, markTextStyle, } = styles;
      const textColor = isTabActive ? '#EA5404' : '#555555';
      const fontWeight = isTabActive ? 'bold' : 'normal';
      const markDom = (this.state.num[page]?<View style={markStyle}><Text style={markTextStyle}>{this.state.num[page]>99?"99+":this.state.num[page]}</Text></View>:null);

      return 
      <Button
        style={{flex: 1, }}
        key={name}
        accessible={true}
        accessibilityLabel={name}
        accessibilityTraits='button'
        onPress={() => onPressHandler(page)}
      >
        <View style={[{flex:1,alignItems: 'center',justifyContent: 'center',paddingBottom: 10}, this.props.tabStyle, ]}>
          <Text style={[textStyle, {color: textColor, fontWeight, }, ]}>
            {name}
          </Text>
          {markDom}
        </View>
      </Button>;
    }

    render() {

        return (
                <ScrollableTabView
                    onChangeTab={this._onChangeTab}
                    locked={true}
                    scrollWithoutAnimation={true}
                    ref={component => this.scrollTab = component}
                    renderTabBar={() => (
                        <DefaultTabBar
                            ref={component => this.tabBar = component}
                            activeTextColor={"#EA5404"}
                            textStyle={styles.textStyle}
                            renderTab={this._renderTab()}
                            markStyle={styles.markStyle}
                            markTextStyle={styles.markTextStyle}
                            underlineStyle={styles.underlineStyle}
                            style={styles.tabBar}
                        />
                    )}>

                    <SellRecordList
                        tabLabel="已完成"
                        tab={0}
                        parent={this}
                        ref={(component) => this._regListView = component }
                        navigator={this.props.navigator}
                        type="complete"/>


                    <SellRecordList
                        tabLabel="已退款"
                        tab={0}
                        parent={this}
                        ref={(component) => this._notApproveListView = component }
                        navigator={this.props.navigator}
                        type="refund"/>

                </ScrollableTabView>

        );
    }
}

var connectHelper = require('../../services/connectHelper');
SellRecordInfo = connectHelper(state => state)(SellRecordInfo);

module.exports = SellRecordInfo;
